package com.lishiots.cloud.datacenter.middleware.web;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lishiots.cloud.datacenter.middleware.common.BuildResult;
import com.lishiots.cloud.datacenter.middleware.common.ErrorConstant;
import com.lishiots.cloud.datacenter.middleware.common.Pagination;
import com.lishiots.cloud.datacenter.middleware.common.RestfulMessage;
import com.lishiots.cloud.datacenter.middleware.entity.User;
import com.lishiots.cloud.datacenter.middleware.req.UserAddRequest;
import com.lishiots.cloud.datacenter.middleware.req.UserLoginRequest;
import com.lishiots.cloud.datacenter.middleware.req.UserQueryRequest;
import com.lishiots.cloud.datacenter.middleware.req.UserUpdateRequest;
import com.lishiots.cloud.datacenter.middleware.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Chaofan at 2018-11-19 14:04
 * email:chaofan2685@qq.com
 **/
@Api(value = "账户管理",tags = "账户管理")
@RestController
@RequestMapping("/api/user")
public class UserController extends BuildResult {

    @Autowired
    UserService userService;

    @ApiOperation(value = "新增用户")
    @PostMapping("/add")
    public RestfulMessage<Boolean> add(UserAddRequest request){
        Assert.notBlank(request.getUserName(),"用户名不能为空");
        Assert.notBlank(request.getPassword(),"密码不能为空");
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name",request.getUserName());
        int count = userService.count(wrapper);
        Assert.isFalse(count>0,"用户名不能重复");
        User user = new User();
        BeanUtils.copyProperties(request,user);
        return mergeObject(userService.save(user));
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/updatePassword")
    public RestfulMessage<Boolean> updatePassword(UserUpdateRequest userUpdate, HttpServletRequest request){
        String userId = (String) request.getSession().getAttribute("USERID");
        Assert.notBlank(userId,"用户未登录");
        User user = userService.getById(userId);
        Assert.notNull(user,"用户不存在");
        Assert.notBlank(userUpdate.getNewPassword(),"新密码不能为空");
        Assert.notBlank(userUpdate.getOldPassword(),"旧密码不能为空");
        Assert.isFalse(userUpdate.getOldPassword().equals(userUpdate.getNewPassword()),"新旧密码不能一致");
        Assert.isTrue(user.getPassword().equals(userUpdate.getOldPassword()),"旧密码错误");
        user.setPassword(userUpdate.getNewPassword());
        return mergeObject(userService.updateById(user));
    }

    @ApiOperation(value = "修改姓名")
    @PostMapping("/updateName")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "name", name = "name"),
    })
    public RestfulMessage<Boolean> updateName(String name, HttpServletRequest request){
        String userId = (String) request.getSession().getAttribute("USERID");
        Assert.notBlank(userId,"用户未登录");
        User user = userService.getById(userId);
        Assert.notNull(user,"用户不存在");
        Assert.notBlank(name,"姓名不能为空");
        user.setName(name);
        return mergeObject(userService.updateById(user));
    }

    @ApiOperation(value = "校验用户名是否重复，true表示不存在重复，可用")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id"),
            @ApiImplicitParam(value = "userName", name = "userName", required = true)
    })
    @GetMapping("/checkUserName")
    public RestfulMessage<Boolean> checkUserName(String id , String userName){
        Assert.notBlank(userName,"用户名不能为空");
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name",userName);
        if (StrUtil.isNotEmpty(id)){
            wrapper.ne("id",id);
        }
        return mergeObject(userService.count(wrapper)<=0);
    }

    @ApiOperation(value = "删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id"),
    })
    @GetMapping("/delete")
    public RestfulMessage<Boolean> delete(String id){
        Assert.notBlank(id,"用户id不能为空");
        return mergeObject(userService.removeById(id));
    }

    @ApiOperation(value = "根据ID获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id"),
    })
    @GetMapping("/queryById")
    public RestfulMessage<User> queryById(String id){
        Assert.notBlank(id,"用户id不能为空");
        return mergeObject(userService.getById(id));
    }

    @ApiOperation(value = "获取所有用户(分页)")
    @PostMapping("/queryPage")
    public Pagination<User> queryPage(UserQueryRequest requestPage){
        PageHelper.startPage(requestPage.getCurrentPage(), requestPage.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name",requestPage.getName());
        wrapper.orderByDesc("create_time");
        List<User> list = userService.list(wrapper);
        PageInfo pageInfo = new PageInfo(list);
        return handlePagination(pageInfo);
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public RestfulMessage<Boolean> login(UserLoginRequest requestUser, HttpServletRequest request){
        HttpSession session = request.getSession();
        RestfulMessage<Boolean> restfulMessage = new RestfulMessage<>();
        Assert.notBlank(requestUser.getUserName(),"用户名不能为空");
        Assert.notBlank(requestUser.getPassword(),"密码不能为空");
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name",requestUser.getUserName());
        User sysUser = userService.getOne(wrapper);
        Assert.notNull(sysUser,"账号不存在");
        Assert.isTrue(requestUser.getPassword().equals(sysUser.getPassword()),"密码错误");
        session.setAttribute("USERID",sysUser.getId());
        //session过期时间暂时设为半个小时
        session.setMaxInactiveInterval(30*60);
        return mergeObject(true);
    }

    @ApiOperation(value = "获得当前用户")
    @GetMapping("/checkLogin")
    public RestfulMessage<User> checkLogin(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("USERID");
        Assert.notNull(obj,"用户未登录");
        User user = userService.getById(obj.toString());
        Assert.notNull(user,"用户不存在");
        return mergeObject(user);
    }

    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public RestfulMessage<Boolean> logout(HttpServletRequest request){
        request.getSession().removeAttribute("USERID");
        RestfulMessage<Boolean> restfulMessage = new RestfulMessage();
        restfulMessage.setCode(ErrorConstant.NOT_LOGIN);
        restfulMessage.setMessage("NOT_LOGIN");
        return restfulMessage;
    }

}
